package com.example.testcontract.adapter;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.testcontract.R;
import com.example.testcontract.activity.CallRecord;
import com.example.testcontract.bean.Dial;

import java.util.List;


/**
 * Created by admin on 2014/9/22.
 */
public class DialAdapter extends ArrayAdapter<Dial> {
    private int resource;
    private int count;
    private List<Dial> objects;

    public DialAdapter(Context context, int resource, List<Dial> objects) {
        super(context, resource, objects);
        this.resource = resource;
        this.objects = objects;
    }

    @Override
    public int getCount() {
        if (count < objects.size())
            return count;
        else
            return objects.size();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LinearLayout layout = null;
        if (convertView == null) {
            layout = (LinearLayout) LayoutInflater.from(getContext()).inflate(resource, null);
        } else {
            layout = (LinearLayout) convertView;
        }

        Dial dial = getItem(position);
        LinearLayout dialItemLayout= (LinearLayout) layout.findViewById(R.id.item_dial);
        final TextView name = (TextView) layout.findViewById(R.id.dial_name);
        final TextView phoneNum = (TextView) layout.findViewById(R.id.dial_phoneNum);
        TextView date = (TextView) layout.findViewById(R.id.time);
        TextView type = (TextView) layout.findViewById(R.id.state);
        ImageView ivMessage = (ImageView) layout.findViewById(R.id.iv_showMessage);
        name.setText(dial.getName());
        phoneNum.setText(dial.getPhoneNumber());
        date.setText(dial.getDate());
        type.setText(dial.getState());

        ivMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("phone", phoneNum.getText());
                intent.setClass(getContext(), CallRecord.class);
                getContext().startActivity(intent);
            }
        });
        dialItemLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String number = phoneNum.getText().toString();
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number));
                getContext().startActivity(intent);
            }
        });

        return layout;
    }

    public void setCount(int count) {
        this.count = count;
    }
}
